package com.common.util.web.directive;

import java.util.Map;

import freemarker.template.TemplateBooleanModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.TemplateNumberModel;
import freemarker.template.TemplateScalarModel;

public class DirectiveUtils {
	private static class MustBooleanException extends TemplateModelException {
		public MustBooleanException(String paramName) {
			super();
		}
	}

	public static Boolean getBool(String name, Map<String, TemplateModel> params) throws TemplateException {
		TemplateModel model = (TemplateModel) params.get(name);
		if (model == null) {
			return null;
		}
		if ((model instanceof TemplateBooleanModel)) {
			return Boolean.valueOf(((TemplateBooleanModel) model).getAsBoolean());
		}
		if ((model instanceof TemplateNumberModel)) {
			return Boolean.valueOf(((TemplateNumberModel) model).getAsNumber().intValue() != 0);
		}
		if ((model instanceof TemplateScalarModel)) {
			String s = ((TemplateScalarModel) model).getAsString();
			if ((s != null) && (!"".equals(s))) {
				return Boolean
						.valueOf((!s.equals("0")) && (!s.equalsIgnoreCase("false")) && (!s.equalsIgnoreCase("f")));
			}
			return null;
		}
		throw new MustBooleanException(name);
	}

	public static Boolean getBool(String name, boolean defValue, Map<String, TemplateModel> params)
			throws TemplateException {
		Boolean b = getBool(name, params);
		return Boolean.valueOf(b == null ? defValue : b.booleanValue());
	}

	private static class MustStringException extends TemplateModelException {
		public MustStringException(String paramName) {
			super();
		}
	}

	public static String getString(String name, Map<String, TemplateModel> params) throws TemplateException {
		TemplateModel model = (TemplateModel) params.get(name);
		if (model == null) {
			return null;
		}
		if ((model instanceof TemplateScalarModel)) {
			return ((TemplateScalarModel) model).getAsString();
		}
		if ((model instanceof TemplateNumberModel)) {
			return ((TemplateNumberModel) model).getAsNumber().toString();
		}
		throw new MustStringException(name);
	}
}
